<?php


use Illuminate\Database\Capsule\Manager as DB;

class Dianpu_InfoController extends CommonController
{
    #[查看店铺信息]
    public function detailAction()
    {
        try {
            $dianpu = \app\modules\Admin\models\dianpuModel::query()
                                                           ->whereIn('id',
                                                                    \app\modules\Admin\models\merchantModel::query()->where('member_id', $this->user->id)->pluck('id')->toArray())
            ->firstOrFail();
            json(['code'=> 1, 'data'=>$dianpu->toArray()]);
        }catch (Exception $e){
            json(['code' => 300, 'msg' => '店铺不存在']);
            exit;
        }
    }

    #[添加店员]
    public function addmemberAction()
    {
        if(!$this->isPost()){
            json(['code' => 0, 'msg' => '请求出错！']);
            exit;
        }
        try {
            $new_member_id = $this->get('members');
            $member_ids = [];
            if(empty($new_member_id)){
                throw new Exception('添加的店员参数出错！', 30001);
            }else{
                if(is_numeric($new_member_id)){
                    $member_ids = [intval($new_member_id)];
                }elseif (is_array($new_member_id)){
                    $member_ids = $new_member_id;
                }else{
                    throw new Exception('添加的店员参数出错！', 30001);
                }
            }
            if(array_search($this->user->id, $member_ids) !== false){
                throw new Exception('添加的店员不能包含自己！', 30001);
            }
            $validate_member_ids = memberModel::query()->whereIn('id', $member_ids)->where('status', 'normal')->pluck('id')->toArray();
            if(empty($validate_member_ids)){
                throw new Exception('添加的店员无效！', 30001);
            }
            $is_dianpu_manager = \app\modules\Admin\models\merchantModel::query()->whereIn('member_id', $validate_member_ids)->pluck('member_id', 'id');
            if(!empty($is_dianpu_manager)){
                throw new Exception('添加的店员已经是其他店铺管理员，请重新添加！', 30001);
            }
            $dianpu = \app\modules\Admin\models\dianpuModel::query()
                                                           ->whereIn('id',
                                                                     \app\modules\Admin\models\merchantModel::query()->where('member_id', $this->user->id)->pluck('id')->toArray())
                                                           ->firstOrFail();
            if($dianpu->status !== 1){
                throw new Exception('店铺已冻结', 30001);
            }
            $res = DB::transaction(function () use ($dianpu, $validate_member_ids){
                $insert_data = [];
                foreach ($validate_member_ids as $id){
                    array_push($insert_data, [
                        'dianpu_id'=>$dianpu->id,
                        'member_id'=>$id,
                        'is_root'=>0,
                        'roles_id'=>0,
                        'created_at'=>timestamp(),
                        'updated_at'=>timestamp(),
                    ]);
                }
                unset($id);
                return \app\modules\Admin\models\merchantModel::query()->insert($insert_data);
            });
            if($res){
                json(['code' => 1, 'msg' => '店员添加成功!']);
                exit;
            }else{
                json(['code' => 0, 'msg' => '添加失败，请重新添加']);
                exit;
            }
        }catch (Exception $e){
            json(['code' => 0, 'msg' => ($e->getCode() !== 30001)?'店铺不存在':$e->getMessage()]);
            exit;
        }
    }

    #[查找目标用户]
    public function getmemberAction()
    {
        if(!$this->isPost()){
            json(['code' => 0, 'msg' => '请求出错！']);
            exit;
        }
        try {
            $keyword = $this->get('keyword');
            //店铺管理员数据量大量，可改成JOIN方式
            $query = memberModel::query()->where('status', 'normal')->whereNotIn('id', \app\modules\Admin\models\merchantModel::query()->pluck('member_id', 'id')->toArray());
            if(!empty($keyword)){
                if(is_numeric($keyword)){
                    $query = $query->where(function ($whereQuery) use($keyword){
                        $whereQuery->where('id', $keyword)->orWhere('phone', 'like', "%{$keyword}%");
                    });
                }
            }
            $member_data = $query->select(['id', 'nickname', 'phone'])->orderByDesc('created_at')->limit(10)->get();
            $data = [];
            if($member_data){
                $data = $member_data->toArray();
            }
            json(['code' => 1, 'msg' => '获取成功', 'data'=>['total'=>count($data), 'rows'=>$data]]);
            unset($data, $query, $keyword, $member_data);
            exit;
        } catch (Exception $e){
            json(['code' => 0, 'msg' => (($e->getCode() === 30001)?$e->getMessage():'请求故障')]);
            exit;
        }
    }
}